#pragma once
#include <cpr/response.h>
#include <elasticlient/client.h>
#include <iostream>
#include <json/json.h>
#include <sstream>

#include "logger.hpp"

namespace im{
    bool Serialize(const Json::Value &val, std::string &dst)
    {
        //先定义Json::StreamWriter 工厂类 Json::StreamWriterBuilder 
        Json::StreamWriterBuilder swb;
        std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());
        //通过Json::StreamWriter中的write接口进行序列化
        std::stringstream ss;
        int ret = sw->write(val, &ss);
        if (ret != 0) {
            LOG_CRITICAL("Json反序列化失败！");
            return false;
        }
        dst = ss.str();
        return true;
    }
    bool UnSerialize(const std::string &src, Json::Value &val)
    {
        Json::CharReaderBuilder crb;
        std::unique_ptr<Json::CharReader> cr(crb.newCharReader());
        std::string err;
        bool ret = cr->parse(src.c_str(), src.c_str() + src.size(), &val, &err);
        if (ret == false) {
            LOG_CRITICAL("json反序列化失败: {}", err);
            return false;
        }
        return true;
    }

    class ESIndex{
    public:
        ESIndex(std::shared_ptr<elasticlient::Client>& client,
                const std::string& name, 
                const std::string& type="_doc")
                :_client(client),_name(name),_type(type){
            // ES请求体固定格式
            Json::Value analysis, analyzer, ik, tokenizer;
            tokenizer["tokenizer"] = "ik_max_word";
            ik["ik"] = tokenizer;
            analyzer["analyzer"] = ik;
            analysis["analysis"] = analyzer;
            _index["settings"] = analysis;
        }

        ESIndex& append(const std::string& key, 
                        const std::string& type = "text",
                        const std::string& analyzer = "ik_max_word",
                        bool enabled = true){
            Json::Value fields;
            fields["type"] = type;
            fields["analyzer"] = analyzer;
            if (enabled == false ) fields["enabled"] = enabled;
            _properties[key] = fields;
            return *this;
        }

        bool create(const std::string& index_id = "default_index_id"){
            Json::Value mappings;
            mappings["dynamic"] = true;
            mappings["properties"] = _properties;
            _index["mappings"] = mappings;

            std::string body;
            if(!Serialize(_index, body)){
                LOG_CRITICAL("索引序列化失败!");
                return false;
            }
            try{
                const cpr::Response& rsp = _client->index(_name, _type, index_id, body);
                if(rsp.status_code < 200 || rsp.status_code >= 300){
                    LOG_CRITICAL("创建ES索引 {} 失败，响应状态码：{}", _name, rsp.status_code);
                    return false;
                }
            }catch(std::exception& e){
                LOG_CRITICAL("创建ES索引{}失败： {}", _name, e.what());
                return false;
            }
            return true;
        }

    private:
        std::string _name;      // 索引名称
        std::string _type;      // 索引类型
        Json::Value _properties;// 字段内容
        Json::Value _index;     // 整个索引
        std::shared_ptr<elasticlient::Client> _client;
    };

    class ESInsert{

    public:
        ESInsert(std::shared_ptr<elasticlient::Client>& client,
            const std::string& name,
            const std::string& type = "_doc")
            :_client(client), _name(name), _type(type){}

        template<typename T>
        ESInsert& append(const std::string& key, const T& val){
            _item[key] = val;
            return *this;
        }

        bool insert(const std::string& index_id = ""){
            std::string body;
            if(Serialize(_item, body) == false){
                LOG_CRITICAL("索引序列化失败！");
                return false;
            }
            LOG_DEBUG("{}", body);
            // 发起新增请求
            try
            {
            auto rsp = _client->index(_name, _type, index_id, body);
            if(rsp.status_code < 200 || rsp.status_code >= 300){
                    LOG_CRITICAL("新增数据 {} 失败，响应状态码异常: {}", body, rsp.status_code);
                    return false;
            }
            }
            catch(const std::exception& e)
            {
                LOG_CRITICAL("新增数据 {} 失败: {}", body, e.what());
                return false;
            }
            return true;
        }

    private:
        std::string _name;
        std::string _type;
        Json::Value _item;  // 新增的数据，以json格式中间存储
        std::shared_ptr<elasticlient::Client> _client;
    };

    class ESSearch{

    public:
        ESSearch(std::shared_ptr<elasticlient::Client> &client, 
            const std::string &name, 
            const std::string &type = "_doc"):
            _name(name), _type(type), _client(client){}

        ESSearch& append_must_not_terms(const std::string& key, const std::vector<std::string>& vals){
            Json::Value fields;
            for(auto& val : vals){
                fields[key].append(val);
            }
            Json::Value terms;
            terms["terms"] = fields;
            _must_not.append(terms);
            return *this;
        }

        ESSearch& append_should_match(const std::string &key, const std::string &val){
            Json::Value field;
            field[key] = val;

            Json::Value match;
            match["match"] = field;

            _should.append(match);
            return *this;
        }

        ESSearch& append_must_term(const std::string &key, const std::string &val){
            Json::Value field;
            field[key] = val;

            Json::Value term;
            term["term"] = field;

            _must.append(term);
            return *this;
        }

        ESSearch& append_must_match(const std::string &key, const std::string &val){
            Json::Value field;
            field[key] = val;

            Json::Value match;
            match["match"] = field;

            _must.append(match);
            return *this;
        }


        Json::Value search(){
            Json::Value cond;
            if(_must_not.empty() == false)
                cond["must_not"] = _must_not;
            if(_should.empty() == false)
                cond["should"] = _should;
            if(_must.empty() == false)
                cond["must"] = _must;

            Json::Value query;
            query["bool"] = cond;
            Json::Value root;
            root["query"] = query;

            // 1.进行序列化
            std::string body;
            if(Serialize(root, body) == false){
                LOG_CRITICAL("索引序列化失败！");
                return Json::Value();
            }

            // 2.发起搜索请求
            cpr::Response rsp;
            try
            {
                rsp = _client->search(_name, _type, body);
                if(rsp.status_code < 200 || rsp.status_code >= 300){
                    LOG_CRITICAL("检索数据 {} 失败，响应状态码异常: {}", body, rsp.status_code);
                    return Json::Value();
                }
            }
            catch(const std::exception& e)
            {
                LOG_CRITICAL("检索数据 {} 失败: {}", body, e.what());
                return Json::Value();
            }

            // 3.需要对正文进行反序列化
            Json::Value result;
            if(UnSerialize(rsp.text, result) == false){
                LOG_CRITICAL("检索数据 {} 结果反序列化失败", rsp.text);
                return Json::Value();
            }

            return result["hits"]["hits"];
        }

    private:
        std::string _name;
        std::string _type;
        Json::Value _must_not;
        Json::Value _should;
        Json::Value _must;
        std::shared_ptr<elasticlient::Client> _client;
    };

    class ESRemove{

    public:
        ESRemove(std::shared_ptr<elasticlient::Client>& client,
            const std::string& name,
            const std::string& type = "_doc")
            :_client(client), _name(name), _type(type){}

        bool remove(const std::string& index_id){
            try
            {
                cpr::Response rsp = _client->remove(_name, _type, index_id);
                if (rsp.status_code < 200 || rsp.status_code >= 300) {
                    LOG_CRITICAL("删除数据 {} 失败，响应状态码异常: {}", index_id, rsp.status_code);
                    return false;
                }
            }
            catch(const std::exception& e)
            {
                LOG_CRITICAL("删除数据 {} 失败: {}", index_id, e.what());
                return false;
            }
            return true;
        }

    private:
        std::string _name;
        std::string _type;
        std::shared_ptr<elasticlient::Client> _client;
    };
}